package org.bing.engine.controller.service;

import java.io.File;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;
import org.bing.engine.controller.lifecycle.GeneralContainerLifecycle;
import org.bing.engine.controller.preference.ConfigurationManager;
import org.bing.engine.core.domain.Application;
import org.bing.engine.core.domain.Container;
import org.bing.engine.core.domain.ContainerInstance;
import org.bing.engine.core.domain.ContainerSetting;
import org.bing.engine.core.service.AbstractContainerLifecycle;
import org.bing.engine.utility.helper.UrlHelper;

/**
 * Manage container(jetty/tomcat) lifecycle.
 * 
 * @author Kevin Chen
 */
public class ContainerManager extends AbstractContainerLifecycle {
    private static final Log logger = LogFactory.getLog(ContainerManager.class);
    protected LocalInstanceManager instance;
    private ConfigurationManager config;
    private ContainerRegistry registry;

    public void setLocalInstanceManager(LocalInstanceManager inst) {
        this.instance = inst;
    }

    public void setConfiguration(ConfigurationManager mgr) {
        this.config = mgr;
    }

    public void setRegistry(ContainerRegistry registry) {
        this.registry = registry;
    }

    @Override
    public void install(Container container) {
        String base = config.getContainerBase();
        String location = base + container.getName() + "-" + container.getVersion() + ".zip";
        File file = new File(location);
        if (file.exists()) {
            // TODO impl file check sum
            logger.info("Container " + container.getName() + "-" + container.getVersion() + " is exist!");
        } else {
            file.getParentFile().mkdirs();
            UrlHelper.readToFile(container.getLocation(), location);
        }
    }

    @Override
    public ContainerInstance startup(ContainerSetting setting, Application application) {
        GeneralContainerLifecycle lifecycle = registry.get(setting.getContainer().getName());
        if (lifecycle != null) {
            ContainerInstance result = lifecycle.startup(setting, application);
            instance.save(result);
            return result;
        } else {
            throw new RuntimeException("Can't find lifecycle for " + setting.getContainer());
        }
    }

    @Override
    public void shutdown(ContainerInstance inst) {
        String name = inst.getSetting().getContainer().getName();
        GeneralContainerLifecycle lifecycle = registry.get(name);
        if (lifecycle != null) {
            lifecycle.shutdown(inst);
            instance.delete(inst);
        } else {
            throw new RuntimeException("Can't find lifecycle for " + name);
        }
    }
}
